package cheme.ProcessModel;

import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sun.org.apache.xerces.internal.impl.xs.identity.Selector.Matcher;

import java.io.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class XmlHelper {

	public static Object xmlFromString(String xmlString)
	{
		Document doc;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		InputSource is = new InputSource();
		is.setCharacterStream(new StringReader(xmlString));
		
		try {
			db = dbf.newDocumentBuilder();
			doc = db.parse(is);
			return doc;
		} catch (ParserConfigurationException e) {
			
			e.printStackTrace();
		} catch (SAXException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		return "error";
	}
	
	public static String xmlToString(Document doc)
	{
		DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
		try {
			transformer = tf.newTransformer();
			transformer.transform(domSource, result);
			String xml = writer.toString();
			
			//before returning, we need to make sure to remove any XML
			//header information that may have been automatically inserted
			//<?xml version="1.0" encoding="UTF-8" standalone="no"?>
			xml = xml.replaceAll("<\\?[\\w =\".-]+\\?>", "");
	       	return xml;
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		return "<error />";
	}
	
}
